import { ConstDefine } from "../../common/ConstDefine";

export default class Star extends fgui.GButton {
    /** 当前类型 */
    public type: number = -1;

    /** 上一次类型 */
    public lastType: number = -1;

    /** 位置编号 */
    private _index: number = -1;
    get index () {
        return this._index;
    }

    set index(value: number){
        this._index = value;
        this._updateLblIndex();
    }

    /** 创建星星 */
    static createStar(){
        fgui.UIObjectFactory.setExtension("ui://Common/btnStar", Star);
        return fgui.UIPackage.createObject(`Common`, `btnStar`) as Star;
    }

    /** 设置类型 */
    setStarType(type: number){
        this.lastType = this.type;
        this.type = type;
    }

    /** 设置图片 */
    setStarImg(type: number){
        let imgStar = this.getChild(`imgStar`).asLoader;
        imgStar.url = `ui://Common/star${type + 1}`;
    }

    /** 设置类型和图片 */
    setStarTypeImg(type: number){
        this.setStarType(type);
        this.setStarImg(type);
    }

    /** 执行翻牌动画并改变类型 */
    runStarActionAndChange(type: number, hookFun: Function = () => {}): Promise<any> {
        return new Promise((res, rej) => {
            if(this.type == type) return;
            this.setStarType(type);
            let eff = this.getTransition(`scale`);
            eff.stop();
            eff.play(res);
            eff.setHook(`change`, () => {
                this.setStarImg(type);
                hookFun();
            });
        });
    }

    /** 根据index设置位置，须先设置父节点 */
    setPosByIndex(index: number, offsetX: number = 0, offsetY: number = 0){
        if (Math.floor(index / 7) % 2 === 0) {
            this.x = (index % 7) * this.width * 1.5 + 46;
        } else {
            this.x = (index % 7) * this.width * 1.5;
        }
        this.y = -(Math.floor(index / 7)) * this.height / 2 + this.parent.height;
        this.x = Math.floor(this.x);
        this.y = Math.floor(this.y);
        this.x += offsetX;
        this.y += offsetY + 27;
    }

    private _updateLblIndex(){
        let lbl = this.getChild(`lblIndex`).asLabel;
        lbl.text = this._index + ``;
        lbl.visible = ConstDefine.Config.App.showStarIndex;
    }
}
